package com.example.demo.project.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.Result;
import com.example.demo.common.annotation.NotNUll;
import com.example.demo.project.entity.Files;
import com.example.demo.project.service.FileService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@ResponseBody
@RequestMapping("/web")
public class WebContentController {
    @Resource
    private FileService fileService;
    @Value("${img.upload.path}")
    private String fileUploadPath;
    @Value("${img.see.path}")
    private String imgSeePath;

    @GetMapping("/list")
    public Result list(){
        int pageSize = 10;
        PageHelper.startPage(1, pageSize);
        List<Files> pageAll = fileService.list();
        PageInfo<Files> pageInfo = new PageInfo<>(pageAll);
        return Result.success(pageInfo);
    }

    @PostMapping("/updateOrInsert")
    public Result update(@NotNUll Long id, MultipartFile img) {
//            String resourceUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "static/files/";
            String resourceUrl = fileUploadPath;
//           找到之前的文件
            Files newFiles=new Files();
            String type = FileUtil.extName(img.getOriginalFilename());
            long size = img.getSize();
            if(id!=null){
                Files files = fileService.getById(id);
                if(files==null){
                    return Result.error(401,"文件id错误");
                }
                newFiles.setId(id);
                File tempFile=new File(files.getUrl());
                //删除以前照片
                String realPath =  resourceUrl+tempFile.getName();
                File fileBefore = new File(realPath);
                //如果原来有图片则删除
                if (fileBefore.exists()) {
                    fileBefore.delete();
                }
            }
            String uuid=IdUtil.fastSimpleUUID();
            String fileUrl = imgSeePath + uuid + img.getOriginalFilename();
            String filePath = resourceUrl + uuid + img.getOriginalFilename();
            File newFile=new File(filePath);
            File parentFile = newFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
            try {
                FileUtil.writeBytes(img.getBytes(), filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String md5 = SecureUtil.md5(newFile);
//            Files dbFiles = getFileByMd5(md5);
//            if(dbFiles !=null){
//                fileUrl = dbFiles.getUrl();
//                newFile.delete();
//            }
            newFiles.setName(img.getOriginalFilename());
            newFiles.setType(type);
            newFiles.setSize(size/1024);
            newFiles.setUrl(fileUrl);
            newFiles.setMd5(md5);
            return Result.success(fileService.saveOrUpdate(newFiles));
    }
    private Files getFileByMd5(String md5){
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5",md5);
        List<Files> filesList = fileService.list(queryWrapper);
        return filesList.size()==0?null:filesList.get(0);
    }
//
//    @PostMapping("/insert")
//    public Result insert(String enTitle, String content, MultipartFile img, MultipartFile imgChange) {
////        if(webContent == null) {
////            return Result.error(500,"对象为空");
////        } else {
//            String imgChangeUrl = "";
//            String fileName = img.getOriginalFilename();
//            System.out.println("fileName:"+fileName);
//            String fileUrl = "/files/" + IdUtil.fastSimpleUUID() + fileName;
//            String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "/static/web-view" + fileUrl;
//            System.out.println("filePath:"+filePath);
//            try {
//                FileUtil.writeBytes(img.getBytes(), filePath);
//                System.out.println("上传文件成功！");
//                Result.success("上传文件成功！");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            if(imgChange != null) {
//                imgChangeUrl = "/files/" + IdUtil.fastSimpleUUID() + imgChange.getOriginalFilename();
//                String imgChangePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "/static/web-view" + imgChangeUrl;
//                System.out.println("imgChangePath:"+imgChangePath);
//                try {
//                    FileUtil.writeBytes(imgChange.getBytes(),imgChangePath);
//                    System.out.println("上传文件成功！!!!");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            WebContent webContent = new WebContent();
//            webContent.setContent(content);
//            webContent.setEnTitle(enTitle);
//            webContent.setImg(fileUrl);
//            webContent.setImgChange(imgChangeUrl);
//            return Result.success(webContentService.insert(webContent));
////        }
//    }
//
//    @PostMapping("/delete")
//    public Result delete(Long id) {
//        if(id == null) {
//            return Result.error(500,"id不能为空");
//        } else {
//            WebContent webContent = webContentService.get(id);
//            String filePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + webContent.getImg();
//            if (webContent.getImgChange() != "") {
//                String imgChangeUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath() + webContent.getImgChange();
//                File file1 = new File(imgChangeUrl);
//                if (file1.exists()) {
//                    file1.delete();
//                }
//            }
//            File file = new File(filePath);
//            //如果原来有图片则删除
//            if (file.exists()) {
//                file.delete();
//            }
//            return Result.success(webContentService.deleteByPrimaryKey(id));
//        }
//    }
}
